using GameFrameWork;
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

/// <summary>
/// 子弹基类
/// </summary>
public class Bullet : MonoBehaviour
{
    public BulletType BulletType { get; private set; }
    private IMovementStrategy m_Movement;
    private List<InstantEffectData> m_Effects;
    protected Entity m_Entity;

    private BulletData m_BulletData;

    /// <summary>
    /// 子弹剩余穿透次数
    /// </summary>
    private int m_Pierce;

    public void Initialize(Entity owner, IMovementStrategy movement)
    {
        this.m_Entity = owner;
        this.m_Movement = movement;

        this.m_BulletData = this.m_Entity.EntityData.AttackData.BulletData;
        this.m_Effects = this.m_BulletData.Effects;

        m_Pierce = this.m_BulletData.MaxPierce;
        
        // 初始化子弹类型
        if (m_BulletData != null)
        {
            BulletType = m_BulletData.BulletType;
        }
        
        DoMove();
    }

    /// <summary>
    /// 获取子弹所有者（供外观类使用）
    /// </summary>
    public Entity GetOwner()
    {
        return m_Entity;
    }

    /// <summary>
    /// 获取移动策略（供外观类使用）
    /// </summary>
    public IMovementStrategy GetMovement()
    {
        return m_Movement;
    }

    private void DoMove()
    {
        Vector3 start = transform.position;

        Vector3 end = new Vector3(10f, start.y, 0);

        var enemy = m_Entity.AttackComponent.FindEnemy();
        if (enemy != null)
        {
            // 保持水平移动：只改变 x 坐标，保持 y 坐标不变
            end = new Vector3(enemy.transform.position.x, start.y, enemy.transform.position.z);
        }

        // 使用 MoveData.Speed 计算移动时间
        float duration = CalculateMoveDuration(start, end);
        m_Movement.Move(transform.gameObject, start, end, duration, OnComplete);
    }

    /// <summary>
    /// 根据 MoveData.Speed 计算移动时间
    /// </summary>
    private float CalculateMoveDuration(Vector3 start, Vector3 end)
    {
        if (m_BulletData == null || m_BulletData.MoveData == null)
        {
            // 降级方案：使用 AttackData.Duration
            return this.m_Entity.EntityData.AttackData.Duration;
        }

        float speed = m_BulletData.MoveData.Speed;
        if (speed <= 0)
        {
            // 如果速度无效，使用 AttackData.Duration 作为降级方案
            Logger.LogWarning("Bullet", $"MoveData.Speed 无效 ({speed})，使用 AttackData.Duration");
            return this.m_Entity.EntityData.AttackData.Duration;
        }

        // 计算距离
        float distance = Vector3.Distance(start, end);
        
        // 根据速度计算时间：时间 = 距离 / 速度
        float duration = distance / speed;
        
        return duration;
    }

    private void OnComplete()
    {
        BulletPool.Instance.ReturnBullet(this);
    }

    protected virtual void OnTriggerEnter2D(Collider2D other)
    {
        Logger.Log($"[Bullet OnTriggerEnter2D] 子弹命中 ===>>> {other.gameObject.name}");
        var entity = other.GetComponent<Entity>();
        if (entity != null)
        {
            Logger.Log("Bullet", $"子弹命中实体: {entity.name}, 效果数量={m_Effects?.Count ?? 0}, 剩余穿透={m_Pierce}");
            
            if (m_Effects == null || m_Effects.Count == 0)
            {
                Logger.LogWarning("Bullet", $"子弹没有效果列表！entity={entity.name}");
            }
            else
            {
                // 执行效果，包括伤害和Buff
                Logger.Log("Bullet", $"开始执行效果，caster={m_Entity?.name}, target={entity.name}");
                
                // 检查是否有增强效果
                var enhancement = GetComponent<BulletEnhancement>();
                if (enhancement != null && (enhancement.DamageMultiplier != 1.0f || enhancement.BonusDamage > 0))
                {
                    // 应用增强效果
                    ApplyEnhancementEffects(entity, enhancement);
                }
                else
                {
                    // 普通子弹，直接执行效果
                    SkillExecutor.Execute(m_Effects, m_Entity, entity);
                }
            }
            
            m_Pierce--;//穿透
            Logger.Log("Bullet", $"穿透后剩余: {m_Pierce}");
        }
        else
        {
            Logger.Log("Bullet", $"命中的对象不是Entity: {other.gameObject.name}");
        }

        if (m_Pierce <= 0)
        {
            Logger.Log("Bullet", $"穿透次数用完，回收子弹");
            OnComplete();
        }
    }

    /// <summary>
    /// 应用增强效果（使用外观模式统一处理）
    /// </summary>
    private void ApplyEnhancementEffects(Entity target, BulletEnhancement enhancement)
    {
        if (target == null || enhancement == null)
        {
            return;
        }

        // 先执行非伤害效果
        foreach (var effect in m_Effects)
        {
            if (!(effect is DamageEffectData))
            {
                effect.Execute(m_Entity, target);
            }
        }

        // 执行增强效果列表中的效果
        if (enhancement.EffectsToAdd != null && enhancement.EffectsToAdd.Count > 0)
        {
            SkillExecutor.Execute(enhancement.EffectsToAdd, m_Entity, target);
        }

        // 计算并应用伤害（应用倍数和额外伤害）
        if (m_Entity != null && m_Entity.AttackComponent != null && m_Entity.AttackComponent.AttackData != null)
        {
            var attackData = m_Entity.AttackComponent.AttackData;
            long baseDamage = attackData.Damage;
            
            // 应用伤害倍数
            long finalDamage = (long)Math.Round(baseDamage * enhancement.DamageMultiplier);
            
            // 应用额外伤害
            if (enhancement.BonusDamage > 0)
            {
                finalDamage += enhancement.BonusDamage;
            }
            
            // 造成伤害
            if (target.HealthComponent != null)
            {
                target.HealthComponent.TakeDamage(finalDamage);
                Logger.Log("Bullet", $"增强子弹造成伤害: {finalDamage} (基础: {baseDamage}, 倍数: {enhancement.DamageMultiplier}, 额外: {enhancement.BonusDamage})");
            }
            
            // 受到伤害时变红
            float colorDuration = attackData.Duration;
            target.SetColor(Color.red, colorDuration);
        }

        // 添加Buff
        if (enhancement.BuffsToAdd != null && enhancement.BuffsToAdd.Count > 0 && target.BuffComponent != null)
        {
            foreach (var buffData in enhancement.BuffsToAdd)
            {
                if (buffData != null)
                {
                    target.BuffComponent.AddBuff(buffData, m_Entity, target);
                    Logger.Log("Bullet", $"增强子弹添加Buff: {buffData.BuffName}");
                }
            }
        }
    }
}

